import {
  set_user_info
} from '../actions/member';

import {
  set_deploy_url,
  set_verify_deploy,
  set_hosts,
  set_dbconnectors,
  add_hosts,
  add_dbconnectors,
  set_branches,
} from '../actions/deploy';

function deploy (state = {
  deployUrl: "",
  deployHost: "",
  deployPort: 9535,
  deployVersion: 0,
  canDeployConnect: false,
  newVersion: null,
  hosts: [],
  dbconnectors: [],
  branches: [],
  databases: [],
}, action) {
  let hosts_tmp;
  let dbconnectors_tmp;
  switch (action.type) {
    case set_user_info:
      return Object.assign({}, state, {
        deployUrl: action.organizeEntity.deployUrl,
        deployVersion: action.organizeEntity.deployVersion,
        deployHost: action.organizeEntity.deployUrl === null ? null : action.organizeEntity.deployUrl.split("/")[2].split(":")[0],
        deployPort: action.organizeEntity.deployUrl === null ? null : action.organizeEntity.deployUrl.split("/")[2].split(":")[1],
      });
    case set_deploy_url:
      return Object.assign({}, state, {
        deployUrl: action.deployUrl,
        deployHost: action.deployUrl.split("/")[2].split(":")[0],
        deployPort: action.deployUrl.split("/")[2].split(":")[1],
        canDeployConnect: true
      });
    case set_verify_deploy:
      return Object.assign({}, state, {
        canDeployConnect: action.result,
        newVersion: action.newVersion
      });
    case set_hosts:
      hosts_tmp = action.list == null ? [] : action.list;
      return Object.assign({}, state, {
        hosts: hosts_tmp
      });
    case add_hosts:
      hosts_tmp = state.hosts;
      if (hosts_tmp.indexOf(action.host) === -1) {
        hosts_tmp.push(action.host)
        return Object.assign({}, state, {
          hosts: hosts_tmp
        });
      } else {
        return state;
      }
    case set_dbconnectors:
      dbconnectors_tmp = action.list == null ? [] : action.list;
      return Object.assign({}, state, {
        dbconnectors: dbconnectors_tmp
      });
    case add_dbconnectors:
      dbconnectors_tmp = state.dbconnectors;
      if (dbconnectors_tmp.indexOf(action.dbconnector) === -1) {
        dbconnectors_tmp.push(action.dbconnector)
        return Object.assign({}, state, {
          dbconnectors: dbconnectors_tmp
        });
      } else {
        return state;
      }
    case set_branches:
      let branches_tmp = action.list == null ? [] : action.list;
      return Object.assign({}, state, {
        branches: branches_tmp
      });
    default:
      return state;
  }
}

export default deploy;